package service

import (
	"context"

	"gitee.com/WisdomClassroom/collectingData/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
)

func (s *Service) UploadContentReadings(ctx context.Context, req *pb.ContentReadings) (*pb.ResponseStatus, error) {
	token := core.NewToken()
	err := token.UnpackToken(req.GetAuthToken(), &core.FlagTokenCert)
	if err != nil {
		return &pb.ResponseStatus{
			Code: pb.ResponseStatusCode_NotAuth, Error: err.Error(),
		}, nil
	}

	contentReadings := make([]interface{}, 0, len(req.GetContentReadings()))
	for _, contentReading := range req.GetContentReadings() {
		contentReadings = append(contentReadings, models.ContentReading{
			UserUUID:    token.UUID,
			StartTime:   contentReading.GetStartTime(),
			EndTime:     contentReading.GetEndTime(),
			ChapterUUID: contentReading.GetChapterUUID(),
		})
	}

	_, err = glb.ContentReadingCollection.InsertMany(ctx, contentReadings)
	if err != nil {
		glb.Logger.Error(err.Error())
		return &pb.ResponseStatus{Code: pb.ResponseStatusCode_ServerError}, nil
	}
	return &pb.ResponseStatus{Code: pb.ResponseStatusCode_Suc}, nil
}
